package com.lear.rrbus.view;

import java.util.Timer;
import java.util.TimerTask;

import android.app.ActionBar;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.UiModeManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.ZoomDensity;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lear.rrbus.R;
import com.lear.rrbus.utils.Utils;

public class LearWebView extends Activity implements OnClickListener {

	static final private int GET_CODE = 0;
	private final Activity activity = this;
	private LinearLayout addressLayout;

	private ImageButton btnAutoR;
	private ImageButton btnAutoRStop;
	private ImageButton btnBack;

	private ImageButton btnBrowse;
	private ImageButton btnGo;
	private ImageButton btnHome;
	private ImageButton btnNext;
	private ImageButton btnRefresh;

	private ImageButton btnDay;
	private ImageButton btnNight;

	private UiModeManager mUiModeManager;
	private View customView;
	private ImageView imgProgress;
	private TextView inputUrlView;

	private boolean isAutoRF;
	private Animation operatingAnim;
	private boolean isNight;

	private TimerTask rfTask;
	private Timer rfTimer;
	private int time;
	private String title;
	private String url;
	private Boolean isBroweOther;
	private WebView webView;

	private void initial() {
		inputUrlView = (TextView) findViewById(R.id.ed_input_url);
		addressLayout = (LinearLayout) findViewById(R.id.layout_address);

		btnBack = (ImageButton) findViewById(R.id.btn_back);
		btnNext = (ImageButton) findViewById(R.id.btn_next);
		btnHome = (ImageButton) findViewById(R.id.btn_home);
		btnGo = (ImageButton) findViewById(R.id.btn_go);
		btnBrowse = (ImageButton) findViewById(R.id.btn_browse);
		btnRefresh = (ImageButton) findViewById(R.id.btn_refresh);
		btnAutoR = (ImageButton) findViewById(R.id.btn_autorefresh);
		btnAutoRStop = (ImageButton) findViewById(R.id.btn_autorefresh_stop);
		imgProgress = (ImageView) findViewById(R.id.btn_progress);
		btnDay = (ImageButton) findViewById(R.id.btn_day);
		btnNight = (ImageButton) findViewById(R.id.btn_night);

		btnBack.setOnClickListener(this);
		btnNext.setOnClickListener(this);
		btnHome.setOnClickListener(this);
		btnGo.setOnClickListener(this);
		btnBrowse.setOnClickListener(this);
		btnRefresh.setOnClickListener(this);
		btnAutoR.setOnClickListener(this);
		btnAutoRStop.setOnClickListener(this);
		btnDay.setOnClickListener(this);
		btnNight.setOnClickListener(this);

		time = 0;
		// Read auto refresh time
		isAutoRF = getPreferences(MODE_PRIVATE)
				.getBoolean(Utils.AUTOREF, false);
		// Night mode
		mUiModeManager = (UiModeManager) getSystemService(UI_MODE_SERVICE);
		// Read mode
		isNight = getPreferences(MODE_PRIVATE).getBoolean(Utils.NIGHTMODE,
				false);
		if (isNight) {
			mUiModeManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
		}
		// Loading process
		operatingAnim = AnimationUtils.loadAnimation(this,
				R.drawable.loading_rotate);
		LinearInterpolator lin = new LinearInterpolator();
		operatingAnim.setInterpolator(lin);
		// ���ô򿪵�ַ����������վ
		inputUrlView.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN) {
					if (keyCode == KeyEvent.KEYCODE_ENTER) {
						searchInternet(inputUrlView.getText().toString());
						// һ��Ҫ����true��������̻ỻ��?						return true;
					}
				}
				return false;
			}
		});

		isBroweOther = getIntent().getBooleanExtra(Utils.BROWSER, false);
		// Remove auto refresh when browser other web page
		if (isBroweOther) {
			getActionBar().setTitle(
					getResources().getString(R.string.title_webview));
			btnAutoR.setVisibility(View.GONE);
			// Hide the actionbar
			getActionBar().hide();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			time = data.getIntExtra(Utils.REFTIME, 0);
			getPreferences(MODE_PRIVATE).edit().putInt(Utils.REFTIME, time)
					.commit();
			if (time > 0) {
				Toast.makeText(
						this,
						getResources().getString(R.string.hint_autorefresh)
								+ "(" + time + "��)", Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public void onBackPressed() {
		if (isBroweOther) {
			new AlertDialog.Builder(this)
					.setTitle(getResources().getString(R.string.hint_quit))
					.setPositiveButton(
							getResources().getString(R.string.btn_ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									webView.clearCache(true);
									finish();
								}
							})
					.setNeutralButton(
							getResources().getString(R.string.hint_cancel),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									return;
								}
							}).show();
		} else {
			super.onBackPressed();
		}
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_refresh:
			webView.reload();
			showProcess();
			break;
		case R.id.btn_autorefresh:
			startActivityForResult(new Intent(this, SettingsView.class),
					GET_CODE);
			break;
		case R.id.btn_autorefresh_stop:
			runRefresh(0);
			Toast.makeText(this,
					getResources().getString(R.string.hint_unautorefresh),
					Toast.LENGTH_SHORT).show();
			break;
		case R.id.btn_back:
			if (webView.canGoBack()) {
				webView.goBack();
			}
			break;
		case R.id.btn_next:
			if (webView.canGoForward()) {
				webView.goForward();
			}
			break;
		case R.id.btn_home:
			title = getResources().getString(R.string.title_webview);
			getActionBar().setTitle(title);
			searchInternet(getResources().getString(R.string.text_homepage));
			isBroweOther = true;
			break;
		case R.id.btn_go:
			searchInternet(inputUrlView.getText().toString());
			isBroweOther = true;
			break;
		case R.id.btn_browse:
			title = getResources().getString(R.string.title_webview);
			getActionBar().setTitle(title);
			if (addressLayout.getVisibility() == View.GONE) {
				addressLayout.setVisibility(View.VISIBLE);
				inputUrlView.requestFocus();
			} else {
				addressLayout.setVisibility(View.GONE);
			}
			break;
		case R.id.btn_day:
			btnDay.setVisibility(View.GONE);
			btnNight.setVisibility(View.VISIBLE);
			isNight = false;
			break;
		case R.id.btn_night:
			btnDay.setVisibility(View.VISIBLE);
			btnNight.setVisibility(View.GONE);
			webView.setBackgroundColor(0);
			webView.setBackgroundColor(Color.GREEN);
			isNight = true;
			break;
		default:
			break;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Fu
		// int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
		// this.getWindow().setFlags(flag, flag);

		// Display the process bar in the actionbar
		requestWindowFeature(Window.FEATURE_PROGRESS);
		settingActionBar();
		// This must be wrote below
		setContentView(R.layout.lear_webview);
		initial();
		settingWebView();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// getMenuInflater().inflate(R.menu.activity_bus_view, menu);
		return true;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		webView.clearCache(true);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_autorefresh:
			if (isAutoRF) {
				runRefresh(0);
				Toast.makeText(this,
						getResources().getString(R.string.hint_unautorefresh),
						Toast.LENGTH_SHORT).show();

			} else {
				runRefresh(20);
				Toast.makeText(
						this,
						getResources().getString(R.string.hint_autorefresh)
								+ "(" + 20 + "��)", Toast.LENGTH_SHORT).show();
			}
			break;
		case android.R.id.home:
			finish();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onPause() {
		super.onPause();
		if (rfTask != null) {
			rfTask.cancel();
		}
		showProcessOff();
		webView.clearCache(true);
		// Save time
		getPreferences(MODE_PRIVATE).edit().putInt(Utils.REFTIME, time)
				.commit();
		// Save mode
		getPreferences(MODE_PRIVATE).edit()
				.putBoolean(Utils.NIGHTMODE, isNight).commit();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// MenuItem menuRefreshItem = menu.findItem(R.id.menu_autorefresh);
		// if (isAutoRF)
		// menuRefreshItem.setTitle(getResources().getString(
		// R.string.menu_unautorefresh));
		// else
		// menuRefreshItem.setTitle(getResources().getString(
		// R.string.menu_autorefresh));
		return true;
	}

	@Override
	public void onRestart() {
		runRefresh(getPreferences(MODE_PRIVATE).getInt(Utils.REFTIME, 0));
		super.onRestart();
	}


	private void runRefresh(int mTime) {
		time = mTime;
		if (rfTimer != null) {
			isAutoRF = false;
			rfTask.cancel();
			rfTimer.cancel();
		}

		if (mTime == 0) {
			isAutoRF = false;
			btnAutoR.setVisibility(View.VISIBLE);
			btnAutoRStop.setVisibility(View.GONE);
			return;
		}

		else if (mTime > 0) {
			isAutoRF = true;
			rfTimer = new Timer();
			rfTask = new TimerTask() {
				@Override
				public void run() {
					if (isAutoRF) {
						webView.reload();
					}
				}
			};
			rfTimer.schedule(rfTask, 1, mTime * 1000);
			btnAutoR.setVisibility(View.GONE);
			btnAutoRStop.setVisibility(View.VISIBLE);
		}
	}


	private void searchInternet(String newUrl) {
		url = newUrl;
		if (!url.startsWith("http://")) {
			url = "http://" + url;
		}
		webView.loadUrl(url);
		showProcess();
		inputUrlView.setText("");
		// Shutdown soft keyboard
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(LearWebView.this
				.getCurrentFocus().getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
		// Shutdown url input
		addressLayout.setVisibility(View.GONE);
	}

	private void settingActionBar() {
		ActionBar mActionBar = getActionBar();
		mActionBar.setDisplayShowHomeEnabled(false);
		mActionBar.setDisplayHomeAsUpEnabled(true);
		mActionBar.setDisplayShowCustomEnabled(true);

		// Add custom view
		customView = getLayoutInflater().inflate(R.layout.custom_view, null);
		mActionBar.setCustomView(customView, new ActionBar.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				Gravity.RIGHT | Gravity.CENTER_VERTICAL));
	}

	private void settingWebView() {
		webView = (WebView) findViewById(R.id.webview);
		// Setting UA
		webView.getSettings().setUserAgentString(
				getResources().getString(R.string.webview_ua));
		// Open JavaScript
		webView.getSettings().setJavaScriptEnabled(true);
		// Open zoom
		webView.getSettings().setSupportZoom(true);
		webView.getSettings().setBuiltInZoomControls(true);
		// Don't display zoom controls
		webView.getSettings().setDisplayZoomControls(false);
		// Adapt the screen
		webView.getSettings().setDefaultZoom(ZoomDensity.MEDIUM);

		// Display process bar
		webView.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int progress) {
				// Process over
				if (progress == 10) {
				}
				if (progress == 100) {
					showProcessOff();
//					if (webView.getTitle().contains("���?)) {
//						LearWebView.this.setTitle(webView.getTitle()
//								.split("���?)[0]);
//					} else if (webView.getTitle().contains("��Ϣ")) {
//						LearWebView.this.setTitle(webView.getTitle()
//								.split("��Ϣ")[0]);
//					}

				}
				activity.setProgress(progress * 100);
			}
		});

		// Setting open url in this browser
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				showProcess();
				isBroweOther = true;
				getActionBar().setTitle(
						getResources().getString(R.string.title_webview));
				return super.shouldOverrideUrlLoading(view, url);
			}
		});

		// Open the url
		if ((url = getIntent().getStringExtra(Utils.BROWSE)) != null) {
			webView.loadUrl(url);
			showProcess();
		}
	}

	private void showProcess() {
		btnRefresh.setVisibility(View.GONE);
		imgProgress.setVisibility(View.VISIBLE);
		if (operatingAnim != null) {
			imgProgress.startAnimation(operatingAnim);
		}
	}

	private void showProcessOff() {
		// btnProgress.setVisibility(View.GONE);
		btnRefresh.setVisibility(View.VISIBLE);
		imgProgress.setVisibility(View.GONE);
		imgProgress.clearAnimation();
	}

}
